﻿using AspNetCoreRateLimit;
using housingsafety.server.Svcs;
using Newtonsoft.Json;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace housingsafety.server.Helpers.RateLimitExt
{
    /// <summary>
    /// 重写使用我们的自己的redis
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RateLimitStore<T> : IRateLimitStore<T>
    {
        private readonly IRedisUtils _redisUtils;

        public RateLimitStore(IRedisUtils redisUtils)
        {
            this._redisUtils = redisUtils;
        }

        public Task SetAsync(string id, T entry, TimeSpan? expirationTime = null, CancellationToken cancellationToken = default)
        {
            return _redisUtils.StringSetAsync(ConstRedisKeys.UserBehaviorCache, id, JsonConvert.SerializeObject(entry), expirationTime);
        }

        public async Task<bool> ExistsAsync(string id, CancellationToken cancellationToken = default)
        {
            var stored = await _redisUtils.StringGetAsync<string>(ConstRedisKeys.UserBehaviorCache, id);
            return !string.IsNullOrEmpty(stored);
        }

        public async Task<T> GetAsync(string id, CancellationToken cancellationToken = default)
        {
            var stored = await _redisUtils.StringGetAsync<string>(ConstRedisKeys.UserBehaviorCache, id);
            if (!string.IsNullOrEmpty(stored))
            {
                return JsonConvert.DeserializeObject<T>(stored);
            }

            return default;
        }

        public Task RemoveAsync(string id, CancellationToken cancellationToken = default)
        {
            return _redisUtils.KeyDeleteAsync(ConstRedisKeys.UserBehaviorCache, id);
        }
    }
}
